<template>
  <ul class="alphabet">
    <li
      class="item"
      v-for="item of letters"
      :key="item"
      :ref="item"
      @touchstart.prevent="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchEnd="handleTouchEnd"
    >{{item}}</li>
  </ul>
</template>

<script>
import { setTimeout } from "timers";
export default {
  name: "CityAlphabet",
  props: {
    allCities: Object
  },
  data() {
    return {
      touchStatus: false,
      firstLetterY: 0,
      timer: null
    };
  },
  updated() {
    this.firstLetterY = this.$refs["A"][0].offsetTop;
  },
  methods: {
    handleTouchStart(e) {
      this.touchStatus = true;
      this.$emit("letter-change", e.target.innerHTML);
    },
    handleTouchMove(e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 89;
          const index = Math.floor((touchY - this.firstLetterY) / 17);
          if (index >= 0 && index < this.letters.length) {
            this.$emit("letter-change", this.letters[index]);
          }
        }, 16);
      }
    },
    handleTouchEnd() {
      this.touchStatus = false;
    }
  },
  computed: {
    letters() {
      const letters = [];
      for (let i in this.allCities) {
        letters.push(i);
      }
      return letters;
    }
  }
};
</script>

<style lang="stylus" scoped>
@import '~@/assets/styles/varibles.styl';

.alphabet {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  top: 1.78rem;
  right: 0;
  bottom: 0;
  width: 0.4rem;

  .item {
    line-height: 0.35rem;
    color: $bgColor;
  }
}
</style>